package com.example.zwlyz.ui.home;

import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.zwlyz.ArticleManager;
import com.example.zwlyz.adapters.ArticleAdapter;
import com.example.zwlyz.ArticleDetailActivity;
import com.example.zwlyz.R;
import com.example.zwlyz.models.Article;

import java.util.List;

public class HomeFragment extends Fragment {

    private RecyclerView recyclerView;
    private ArticleAdapter articleAdapter;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);

        recyclerView = view.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        loadArticles();

        return view;
    }

    private void loadArticles() {
        List<Article> articles = ArticleManager.getAllArticles();
        articleAdapter = new ArticleAdapter(articles, article -> {
            Intent intent = new Intent(getContext(), ArticleDetailActivity.class);
            intent.putExtra("article", article);
            startActivity(intent);
        });
        recyclerView.setAdapter(articleAdapter);
    }
}